package com.renwei.yunlong;

import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.mob.MobSDK;
import com.renwei.yunlong.activity.me.EnterpriseInformationActivity;
import com.renwei.yunlong.activity.me.KnowInformationActivity;
import com.renwei.yunlong.activity.me.ObjectInformationtActivity;
import com.renwei.yunlong.activity.news.MessageCompanyActivity;
import com.renwei.yunlong.activity.news.MessageDetailActivity;
import com.renwei.yunlong.activity.work.ComplaintsInformationActivity;
import com.renwei.yunlong.activity.work.SpareInformationActivity;
import com.renwei.yunlong.activity.work.WorkInformationActivity;
import com.renwei.yunlong.utils.ACache;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.PackageUtils;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixManager;
import com.taobao.sophix.listener.PatchLoadStatusListener;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.wanjian.cockroach.Cockroach;

import org.litepal.LitePal;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by Administrator on 2017/8/23.
 */

public class YunLongApplication extends Application {

    private static YunLongApplication instance;
    private static String companyType;
    private static String deviceToken; //友盟token
    public static String BASE_URL;
//        public static final String defaultLocalServerIP = "106.14.20.156";
//    public static final String defaultLocalServerPort = "443";
//    public static final String defaultLocalHtp = "https://";
    //本机服务器
    public static final String defaultLocalServerIP = "192.168.15.90";
    public static final String defaultLocalServerPort = "8080";
    public static final String defaultLocalHtp = "http://";

    @Override
    public void onCreate() {
        super.onCreate();
        x.Ext.init(this);
        LitePal.initialize(this);
        instance = this;
        // 百度地图 初始化
        SDKInitializer.initialize(this);
        // 刷新
        initRefresh();
        // 打不死的小强
        initCockroach();
        // 腾讯浏览器
        initWebView();
        // 热更新
        SophixManager.getInstance().queryAndLoadNewPatch();
        // 友盟
        initUMeng();
    }


    private void initUMeng() {
        try {
            // 友盟
            MobSDK.init(this);
            MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
            QbSdk.initX5Environment(this, null);
            // push
            PushAgent mPushAgent = PushAgent.getInstance(this);
            mPushAgent.setDebugMode(false);
            // 设置推送点击跳转
            mPushAgent.setNotificationClickHandler(notificationClickHandler);
            mPushAgent.setMessageHandler(messageHandler);
            //设置 最多接受的推送消息数量
//            mPushAgent.setDisplayNotificationNumber(10);
            //注册推送服务，每次调用register方法都会回调该接口
            mPushAgent.register(new IUmengRegisterCallback() {
                @Override
                public void onSuccess(String deviceToken) {
                    //注册成功会返回device token
                    LogUtil.e("deviceToken" + deviceToken);
                    YunLongApplication.deviceToken = deviceToken;
                }

                @Override
                public void onFailure(String s, String s1) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initWebView() {
        //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.e("app", " =========onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    /**
     * 初始化 打不死的小强
     */
    private void initCockroach() {
        Cockroach.install(new Cockroach.ExceptionHandler() {
            @Override
            public void handlerException(final Thread thread, final Throwable throwable) {
                //由于handlerException可能运行在非ui线程中,
                // 所以new了一个new Handler(Looper.getMainLooper())
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Log.e("AndroidRuntime", "--->CockroachException:" + thread + "<---", throwable);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    ACache.get(instance).clear();
                                    Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
                                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent);
                                }
                            }, 500);
                        } catch (Exception e) {

                        }
                    }
                });
            }
        });
    }

    /**
     * 初始化刷新
     */
    private void initRefresh() {
        //static 代码段可以防止内存泄露
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.bg_color, R.color.color_666666);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.bg_color, R.color.color_666666);//全局设置主题颜色
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
        initSophix();
    }

    private void initSophix() {
        SophixManager.getInstance().setContext(this)
                .setAppVersion(PackageUtils.getVersionName(this))
                .setEnableDebug(true)
                .setPatchLoadStatusStub(new PatchLoadStatusListener() {
                    @Override
                    public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) {
                        // 补丁加载回调通知
                        if (code == PatchStatus.CODE_LOAD_SUCCESS) {
                            // 表明补丁加载成功
                        } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
                            // 表明新补丁生效需要重启. 开发者可提示用户或者强制重启;
                            // 建议: 用户可以监听进入后台事件, 然后调用killProcessSafely自杀，以此加快应用补丁，详见1.3.2.3
                            SophixManager.getInstance().killProcessSafely();
                        } else {
                            // 其它错误信息, 查看PatchStatus类说明
                        }
                    }
                }).initialize();
    }

    /**
     * 友盟推送 事件点击自定义处理
     */
    UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
        @Override
        public void dealWithCustomAction(Context context, UMessage msg) {
            // 跳转
            Map<String, String> map = msg.extra;
            switch (map.get("type")) {
                case "16":// 知识库查询
                    KnowInformationActivity.OpenActivity(YunLongApplication.getInstance(), map.get("relationId"));
                    break;
                case "61": //企业认证通过
                    Intent intent = new Intent(YunLongApplication.getInstance(), EnterpriseInformationActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    break;
                case "7": //申请好友企业
                    MessageCompanyActivity.OpenActivity(YunLongApplication.getInstance());
                    break;
                case "0": //工单
                    WorkInformationActivity.OpenActivity(YunLongApplication.getInstance(),
                            map.get("relationId"), map.get("serverId"), map.get("outsourceFlag"));
                    break;
                case "41": //备件
                    SpareInformationActivity.OpenActivity(YunLongApplication.getInstance(),
                            map.get("requestId"), map.get("outsourceFlag"), map.get("relationId"));
                    break;
                case "3": //对象
                    LogUtil.e("123123131313123");
                    ObjectInformationtActivity.OpenAcitivity(YunLongApplication.getInstance(),
                            "对象详情", map.get("outsourceFlag"), map.get("relationId"), map.get("hardName"));
                    break;
                case "2": //投诉
                    ComplaintsInformationActivity.OpenActivity(YunLongApplication.getInstance(), map.get("requestId"), map.get("newRequestId")
                            , map.get("serverRequestId"), map.get("serverId"), map.get("outsourceFlag"), map.get("relationId"), map.get("senUserName"));
                    break;
                case "54": // 项目到期
                    MessageDetailActivity.OpenActivity(YunLongApplication.getInstance(), Integer.parseInt(map.get("messageId")));
                    break;
                default:
                    break;
            }
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("messageId", map.get("messageId"));
            ServiceRequestManager.getManager().getMessageDetail(YunLongApplication.getInstance(), JsonMapUtil.mapToJson(hashMap), null);
        }

    };

    /**
     * 友盟推送 自定义通知栏
     */
    UmengMessageHandler messageHandler = new UmengMessageHandler() {
        @Override
        public Notification getNotification(Context context, UMessage msg) {
            switch (msg.builder_id) {
//                case 0: //默认为0，若填写的builder_id并不存在，也使用默认。
//                    Notification.Builder builder = new Notification.Builder(context);
//                    RemoteViews myNotificationView = new RemoteViews(context.getPackageName(),
//                            com.umeng.message.lib.R.layout.upush_notification);
//                    myNotificationView.setTextViewText(R.id.notification_title, msg.title);
//                    myNotificationView.setTextViewText(R.id.notification_text, msg.text);
//                    myNotificationView.setImageViewBitmap(R.id.notification_large_icon1,
//                            getLargeIcon(context, msg));
//                    myNotificationView.setImageViewResource(R.id.notification_large_icon1,
//                            getSmallIconId(context, msg));
//                    builder.setContent(myNotificationView)
//                            .setSmallIcon(getSmallIconId(context, msg))
//                            .setTicker(msg.ticker)
//                            .setAutoCancel(true);
//
//                    return builder.getNotification();
                default:
                    return super.getNotification(context, msg);
            }
        }
    };


    public static YunLongApplication getInstance() {
        return instance;
    }

    public static String getCompanyType() {
        return companyType == null ? "2" : companyType;
    }

    public static String getDeviceToken() {
        return deviceToken == null ? "" : deviceToken;
    }

    public static void setCompanyType(String companyType) {
        YunLongApplication.companyType = companyType;
    }

}
